package com.example.daojdbc;

import java.sql.*;

public class DBHelper {

    public Connection getConn() {
        return conn;
    }

    Connection conn = null;
    PreparedStatement pst;
    ResultSet rSet;

    public void init(){
        // 不同的数据库有不同的驱动
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1/test";
        String user = "db_testuser";
        String password = "MyNewPass4!";

        try {
            // 加载驱动
            Class.forName(driverName);
            // 设置 配置数据
            // 1.url(数据看服务器的ip地址 数据库服务端口号 数据库实例)
            // 2.user
            // 3.password
            conn = DriverManager.getConnection(url, user, password);
            // 开始连接数据库
            System.out.println("数据库连接成功..");
        } catch (ClassNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

    }

    public void initConn() throws Exception {
        if (conn == null || conn.isClosed()) {
            this.init();
        }

    }

    public void close() throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.close();
            conn = null;

        }
    }

    public void setAutoCommit(boolean fals) throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.setAutoCommit(fals);
        }
    }

    public void setSavepoint() throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.setSavepoint();
        }
    }

    public void rollback() throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.rollback();
        }
    }

    public void commit() throws Exception {
        if (conn != null && !conn.isClosed()) {
            conn.commit();
        }
    }

}
